package com.breaktian.assemble.socket;


import com.breaktian.assemble.socket.callback.ListenTcpCallBack;
import com.breaktian.assemble.socket.tcp.TcpServerSocketTwo;
import com.breaktian.assemble.socket.tcp.TcpSocketTwo;
import com.breaktian.assemble.socket.tcp.TcpStateListener;

/**
 * 处理wifi直连之间的通讯
 * @author csy
 *
 */

public class MySocketUtil {
	private TcpServerSocketTwo mServerSocket ;
	private TcpSocketTwo mClientTcpSocket;
	
	public MySocketUtil(){
		mClientTcpSocket = new TcpSocketTwo();
	}

	
	/**
	 * 启动服务器监听端口 和回调数据
	 * @param port
	 */
	public void initServer(int port){
		mServerSocket = new TcpServerSocketTwo(port);	
	}
	
	public void serverListen( final ListenTcpCallBack dataReceive){
		new Thread(new Runnable() {
			@Override
			public void run() {
				if(mServerSocket != null){
					mServerSocket.listen(dataReceive);
				}
			}
		}).start();
	}
	
	
	public void setSeverTCPConnetStateListener(TcpStateListener tcpStateListener){
		if(mServerSocket != null){
			mServerSocket.setTcpStateListener(tcpStateListener);
		}
	}
	
	/**
	 * 服务器端写数据
	 * @param str
	 */
	public void serverSend(String str){
		if(mServerSocket != null){
			mServerSocket.send(str);
		}
	}
	
	
	/**
	 * 服务端关闭连接
	 */
	public void serverCloseConnect(){
		if(mServerSocket != null){
			mServerSocket.shutDown();
		}
	}
	
	
	/**
	 * 客户端连接服务器端口
	 * @param remoteIp
	 * @param remotePort
	 */
	public void clientConnectServer(String remoteIp, int remotePort,final ListenTcpCallBack listenTcpCallBack){
		mClientTcpSocket.connect(remoteIp, remotePort);
		mClientTcpSocket.listen(listenTcpCallBack);
	}
	
	
	/**
	 * 客户端往服务器发数据
	 * @param data
	 */
	public void clientSend(String data){
		if(mClientTcpSocket != null){
			mClientTcpSocket.send(data);
		}
	}
	
	public void setClientTCPConnetStateListener(TcpStateListener tcpStateListener){
		if(mClientTcpSocket != null){
			mClientTcpSocket.setTcpStateListener(tcpStateListener);
		}
	}
	
	
	/**
	 * 客户端关闭连接
	 */
	public void clientCloseConnect(){
		if(mClientTcpSocket != null){
			mClientTcpSocket.closeSocket();
		}
	}
	
}
